package com.hcbd.tdwt.ui.htct.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.hcbd.tdwt.ui.fuda.setting.activity.ChannelSetActivity_;


import com.hcbd.tdwt.base.BaseFragment;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.ui.common.dialog.UpgradeDialog;
import com.hcbd.tdwt.ui.setting.hlct.AboutActivity_;
import com.hcbd.tdwt.ui.setting.hlct.AudioPicSettingActivity_;
import com.hcbd.tdwt.util.AppUtil;
import com.hcbd.tdwt.ui.htct.activity.BdSetActivity_;

import com.pangu.bdsdk2021.entity.terminalthree.BDSnrInfo;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;

@SuppressLint("NonConstantResourceId")
@EFragment(R.layout.fragment_my_tiantong)
public class MyFragment extends BaseFragment {
    @ViewById
    TextView title,deviceName,batteryTv,notConTv,deviceConTv,deviceId;
    @ViewById
    ImageView connectPhoneImg,connectPointImg,connectRouteImg,connectTwoPointImg,connectSatelliteImg,conStatusImg;
    @ViewById
    RelativeLayout topRL;
    @ViewById
    ImageButton headLeft;
    @ViewById
    LinearLayout bluetoothLL;
    private final int BLUETOOTH_CONNECT_CODE=15;//蓝牙连接返回

    @AfterViews
    protected void init() {
        topRL.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.top_bg_hlct));
        title.setVisibility(View.GONE);
        headLeft.setVisibility(View.GONE);
        refreshStatus();
        initMsgRegister();
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(String bleContent){
        refreshStatus();
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void eventBus(BDSnrInfo bdSnrInfo){
        int signal=BeidouBoxParams.getBdSignal();
        if(signal>=GlobalParams.sendBeidouMsgSignalEnable){
            connectTwoPointImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_green_point_tt));
            connectSatelliteImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_satellite_tt));
        }else{
            connectTwoPointImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_red_point_tt));
            connectSatelliteImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_satellite_tt));
        }
    }
    @Click
    void connectLL(){
        if(BeidouBoxParams.isBoxConnectNormal){
            BdToolFactory.getBdSendBase().close(getActivity());
        }else {
            BdToolFactory.getBdSendBase().open(getActivity(),BLUETOOTH_CONNECT_CODE);
        }
    }
    @OnActivityResult(BLUETOOTH_CONNECT_CODE)
    void BlueToothConnectResult(){
        refreshStatus();
    }
    private void refreshStatus() {
        batteryTv.setText(MessageFormat.format("电量:{0}%", BeidouBoxParams.kwh));
        if (BeidouBoxParams.isBoxConnectNormal) {
            conStatusImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_succes_tt));
            deviceName.setText(MessageFormat.format("蓝牙名称：{0}", BeidouBoxParams.blueName));
            deviceId.setText(MessageFormat.format("终端ID：{0}", BeidouBoxParams.userCardNumber));
            notConTv.setVisibility(View.GONE);
            bluetoothLL.setVisibility(View.VISIBLE);
            connectPhoneImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_phone_tt));
            connectPointImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_green_point_tt));
            connectRouteImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_route_tt));
            deviceConTv.setVisibility(View.GONE);
            int signal=BeidouBoxParams.getBdSignal();
            if(signal>=GlobalParams.sendBeidouMsgSignalEnable){
                connectTwoPointImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_green_point_tt));
                connectSatelliteImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_satellite_tt));
            }else{
                connectTwoPointImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_red_point_tt));
                connectSatelliteImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_satellite_tt));
            }
        } else {
            conStatusImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_tt));
            deviceName.setText("--");
            notConTv.setVisibility(View.VISIBLE);
            bluetoothLL.setVisibility(View.GONE);
            deviceName.setText("蓝牙名称：--");
            batteryTv.setText("电量:--");
            deviceConTv.setVisibility(View.VISIBLE);
            connectPhoneImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_phone_tt));
            connectPointImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_red_point_tt));
            connectRouteImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_route_tt));
            connectTwoPointImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_red_point_tt));
            connectSatelliteImg.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.connect_not_satellite_tt));
        }
    }
    @Override
    public void  onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            //不可见
            EventBus.getDefault().unregister(this);
        }else{
            refreshStatus();
            EventBus.getDefault().register(this);
        }
    }
    @Click
    void bdSetLL(){
        Intent intent=new Intent(getContext(), BdSetActivity_.class);
        startActivity(intent);
    }
    @Click
    void offMapLL(){
        startActivity(new Intent(this.getContext(), com.amap.api.maps.offlinemap.OfflineMapActivity.class));
    }
    @Click
    void authInfoRL(){
        Intent intent=new Intent(getContext(), AudioPicSettingActivity_.class);
        startActivity(intent);
    }
    @Click
    void aboutLL(){
        Intent intent=new Intent(getContext(), AboutActivity_.class);
        startActivity(intent);
    }
    @Click
    void appUpgradeLL(){
        if(!AppUtil.isHaveNetwork()){
            toast("请打开网络！");
            return;
        }
        showLoading("检测当前版本中");
        new PgyUpdateManager.Builder()
                .setForced(true)                //设置是否强制提示更新,非自定义回调更新接口此方法有用
                .setUserCanRetry(false)         //失败后是否提示重新下载，非自定义下载 apk 回调此方法有用
                .setDeleteHistroyApk(true)     // 检查更新前是否删除本地历史 Apk， 默认为true
                .setUpdateManagerListener(new UpdateManagerListener() {
                    @Override
                    public void onNoUpdateAvailable() {
                        //没有更新是回调此方法
                        Log.e("pgyer", "there is no new version");
                        hideLoading();
                        toast("当前没有新版本！");
                    }
                    @Override
                    public void onUpdateAvailable(AppBean appBean) {
                        //有更新回调此方法
                        Log.e("pgyer", "there is new version can update"
                                + "new versionCode is " + appBean.getVersionCode());
                        //调用以下方法，DownloadFileListener 才有效；
                        hideLoading();
                        //如果完全使用自己的下载方法，不需要设置DownloadFileListener
                        new UpgradeDialog(getContext(), appBean.getVersionName(), appBean.getReleaseNote(), dialog -> PgyUpdateManager.downLoadApk(appBean.getDownloadURL())).show();


                    }

                    @Override
                    public void checkUpdateFailed(Exception e) {
                        //更新检测失败回调
                        //更新拒绝（应用被下架，过期，不在安装有效期，下载次数用尽）以及无网络情况会调用此接口
                        hideLoading();
                        toast("网络有误!");
                        Log.e("pgyer", "check update failed ", e);
                    }
                }).register();
    }
    @Click
    void centerNumberLL(){
        Intent intent=new Intent();
        intent.setClass(getContext(), ChannelSetActivity_.class);
        startActivity(intent);
    }
}
